var gulp = require('gulp');
var uglifyjs = require("gulp-uglify");
var uglifycss = require("gulp-minify-css");
var uglifyhtml = require("gulp-minify-html");
var uglifyimages = require("gulp-imagemin");
var jshint = require("gulp-jshint");
var concatjs = require("gulp-concat");
var renamejs = require("gulp-rename");
var lesscs = require("gulp-less");
var livereload = require("gulp-livereload");


// js文件与压缩任务
gulp.task("JSuglify", function() {
	// 这里要做压缩js的任务
	// gulp.src(["src/js/index.js", "src/js/tools.js"])
	gulp.src("src/js/apps/*.js")
		.pipe(uglifyjs())
		.pipe(gulp.dest("dist/js/apps"))
});

// 压缩css文件
gulp.task("cssuglify", function() {
	gulp.src("src/css/init.css")
		.pipe(uglifycss())
		.pipe(gulp.dest("dist/css"))
});

// 压缩HTML文件
gulp.task("htmluglify", function() {
	gulp.src("src/index.html")
		.pipe(uglifyhtml())
		.pipe(gulp.dest("dist"))
});

// http://blog.csdn.net/u013063153/article/details/52628506
// 压缩图片
gulp.task("imageuglify", function() {
	gulp.src("src/images/*.{png,jpg,gif,ico,jpeg}")
		.pipe(uglifyimages({
			progressive: true, // 压缩无损图片
			multipass: true // 多次优化svg直到完全优化
		}))
		.pipe(gulp.dest("dist/images"))
});

// 代码检查
gulp.task("hintjs", function() {
	gulp.src("src/js/apps/*.js")
		.pipe(jshint())
		.pipe(jshint.reporter());
});

// 压缩、合并、重命名
gulp.task("final", function() {
	gulp.src("src/js/apps/*.js")
		.pipe(concatjs("app.js")) // 合并之后叫什么名字
		.pipe(uglifyjs())
		.pipe(renamejs({
			suffix: ".min"
		}))
		.pipe(gulp.dest("dist/js/apps/final"))
});

// 监听
gulp.task("watch", function() {
	gulp.watch('src/js/apps/*.js', function() {
		gulp.run('final');
	});
});

// 编译less文件
gulp.task("lesscss", function() {
	gulp.src("src/css/demo.less")
		.pipe(lesscs())
		.pipe(gulp.dest("dist/css"))
});


// 热更新
gulp.task("hot", function() {
	livereload.listen();
	gulp.watch('src/index.html', function(event) {
		livereload.changed(event.path);
	});
});

gulp.task('default', function() {
	gulp.start(["JSuglify"]);
});